package com.wish233.application;

import com.wish233.config.RegistryConfig;
import com.wish233.config.RpcConfig;
import com.wish233.register.Registry;
import com.wish233.register.factory.RegistryFactory;
import com.wish233.utils.ConfigUtils;
import lombok.extern.slf4j.Slf4j;

import static com.wish233.constant.RpcConstant.PREFIX;


/**
 * @author WHH
 */
@Slf4j
public class RpcApplication {
    private static volatile RpcConfig rpcConfig;

    private static void init(RpcConfig newRpcConfig) {
        rpcConfig = newRpcConfig;
        //注册中心初始化
        registryInit();
        log.info("wrpc配置文件加载成功！内容如下");
        log.info(rpcConfig.toString());
    }

    public static void init() {
        RpcConfig newRpcConfig;
        try {
            newRpcConfig = ConfigUtils.loadConfig(RpcConfig.class, PREFIX);
            newRpcConfig.setRegistryConfig(ConfigUtils.loadConfig(RegistryConfig.class, PREFIX + ".registry"));
        } catch (Exception e) {
            log.info("配置文件加载失败，使用默认配置文件");
            log.info("错误信息: {}", e.getMessage());
            newRpcConfig = new RpcConfig();
        }
        init(newRpcConfig);
    }


    public static RpcConfig getRpcConfig() {
        if (rpcConfig == null) {
            synchronized (RpcApplication.class) {
                if (rpcConfig == null) {
                    init();
                }
            }
        }
        return rpcConfig;
    }

    private static void registryInit() {
        // 注册中心初始化
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);
        log.info("注册中心初始化, config = {}", registryConfig);
    }
}
